import json
import requests
import os

#
# 美团收银系统
#

def main():
    # 确保 pic 文件夹存在
    if not os.path.exists("pic"):
        os.makedirs("pic")

    # 从 response.json 文件中读取 JSON 数据
    with open("response.json", "r", encoding="utf-8") as file:
        data = json.load(file)

    # 遍历 foods 列表
    for food in data["data"]["goods"]:
        name = food["name"]
        image_url = food["imgUrl"]

        if not image_url:
            continue
        # 清理文件名中的特殊字符
        safe_name = name.replace("【", "").replace("】", "").replace("/", "_").replace("\\", "_")
        safe_name = safe_name + "-1"
        # 下载图片
        try:
            response = requests.get(image_url)
            response.raise_for_status()  # 检查请求是否成功
            image_data = response.content

            # 保存图片到 pic 文件夹
            file_path = os.path.join("pic", f"{safe_name}.jpeg")
            with open(file_path, "wb") as file:
                file.write(image_data)
            print(f"图片已保存为 {file_path}")
        except requests.exceptions.RequestException as e:
            print(f"下载图片失败，URL: {image_url}，错误信息: {e}")
            print("请检查网页链接的合法性或稍后重试。")

if __name__ == '__main__':
    main()